import {
  type ChangeEvent,
  type FormEvent,
  useContext,
  useRef,
  useState,
} from 'react';
import useToast from '@/hooks/useToast';
import { useMutation } from '@tanstack/react-query';
import { queryQqAuthUrl } from '@/services/api';
import Link from 'next/link';
import { RegisterPageContext } from '@/contexts/register';

export default function QqRegister() {
  const {
    source: { path: data, registerConfig },
    translatedFields,
  } = useContext(RegisterPageContext)!;
  const [form, setForm] = useState({
    alias: '',
    isAgreeAgreement: false,
  });
  const [disableRegister, setDisableRegister] = useState(false);
  const agreementInputRef = useRef<HTMLInputElement>(null);
  const { show } = useToast();

  const queryQqAuthUrlMutation = useMutation(queryQqAuthUrl);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const { alias, isAgreeAgreement } = form;
      const qqConfig = data.qqConfig;
      if (registerConfig.enableRegistrationConsent && !isAgreeAgreement) {
        agreementInputRef.current?.focus();
        show({
          type: 'DANGER',
          message: translatedFields.agreeBeforeRegister,
        });
        return;
      }

      if (!qqConfig || !qqConfig.enable) {
        show({
          type: 'DANGER',
          message: translatedFields.tencentQQRegistrationDisabled,
        });
        return;
      }

      const url = (await queryQqAuthUrlMutation.mutateAsync({
        data: { alias },
      })) as string;
      setDisableRegister(true);

      show({
        message: translatedFields.enterTencentQQAuthorization,
        type: 'PRIMARY',
      });

      setTimeout(() => {
        show({
          message: translatedFields.redirect,
          type: 'PRIMARY',
        });
      }, 1000);

      setTimeout(() => {
        location.href = url;
      }, 1500);
    } catch (e) {
      queryQqAuthUrlMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'agreement') {
      setForm({ ...form, isAgreeAgreement: !form.isAgreeAgreement });
    } else {
      setForm({ ...form, [name]: value.trim() });
    }
  }

  return (
    <form onSubmit={onSubmit}>
      <div className="my-3">
        <label className="form-label">{translatedFields.aliasOptional}</label>
        <input
          value={form.alias}
          onChange={onChangeForm}
          name="alias"
          type="text"
          className="form-control"
          placeholder={translatedFields.enterAlias}
          aria-describedby={translatedFields.enterAlias}
        />
      </div>

      {data.qqConfig && data.qqConfig.enable ? (
        <div className="my-3">
          <button
            disabled={queryQqAuthUrlMutation.isLoading || disableRegister}
            type="submit"
            className="btn btn-outline-primary mt-4 mb-3 w-100"
          >
            {queryQqAuthUrlMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            {disableRegister ? (
              <span>{translatedFields.redirect}</span>
            ) : (
              <span>{translatedFields.quickRegistration}</span>
            )}
          </button>
        </div>
      ) : (
        <div className="my-3">
          <button
            disabled
            type="submit"
            className="btn btn-outline-primary mt-4 mb-3 w-100"
          >
            {translatedFields.tencentQQRegistrationDisabled}
          </button>
        </div>
      )}

      {registerConfig.enableRegistrationConsent && (
        <div className="form-check my-3">
          <input
            ref={agreementInputRef}
            name="agreement"
            value="agreement"
            onChange={onChangeForm}
            type="checkbox"
            className="form-check-input cursor-pointer"
          />
          <label className="form-check-label user-select-none">
            <span>{translatedFields.readAndAgree}</span>
            <Link href={registerConfig.terms ?? '/terms'}>
              {translatedFields.serviceAgreement}
            </Link>
            <span>{translatedFields.and}</span>
            <Link href={registerConfig.privacyPolicy ?? '/privacy-policy'}>
              {translatedFields.privacyPolicy}
            </Link>
          </label>
        </div>
      )}
    </form>
  );
}
